<template>
  <div class="app-container">
    <!-- 精简的搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="产品编码" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="产品名称" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="queryParams.brand" placeholder="品牌" clearable style="width: 120px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input v-model="queryParams.model" placeholder="型号" clearable style="width: 120px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="产品状态" clearable style="width: 120px">
          <el-option label="下架" :value="0" />
          <el-option label="上架" :value="1" />
          <el-option label="预售" :value="2" />
          <el-option label="缺货" :value="3" />
          <el-option label="停产" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="审核状态" clearable style="width: 120px">
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="支持购买" prop="isBuyable">
        <el-select v-model="queryParams.isBuyable" placeholder="支持购买" clearable style="width: 120px">
          <el-option label="仅租赁" :value="0" />
          <el-option label="支持购买" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="供应商名称" clearable style="width: 140px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:rentalDeviceProducts:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:rentalDeviceProducts:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:rentalDeviceProducts:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:rentalDeviceProducts:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 优化的表格展示 -->
    <el-table 
      v-loading="loading" 
      :data="rentalDeviceProductsList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      size="small"
      class="common-table"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="productId" width="80" />
      <el-table-column label="产品编码" align="center" prop="productCode" width="140" show-overflow-tooltip />
      <el-table-column label="产品名称" align="left" prop="productName" min-width="180" show-overflow-tooltip />
      <el-table-column label="主图" align="center" prop="mainImage" width="80">
        <template slot-scope="scope">
          <image-preview :src="scope.row.mainImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brand" width="100" show-overflow-tooltip />
      <el-table-column label="型号" align="center" prop="model" width="120" show-overflow-tooltip />
      <el-table-column label="日租金" align="center" prop="baseDailyRent" width="80">
        <template slot-scope="scope">
          <span style="color: #E6A23C;">¥{{ scope.row.baseDailyRent }}</span>
        </template>
      </el-table-column>
      <el-table-column label="一口价" align="center" prop="buyPrice" width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.buyPrice" style="color: #F56C6C;">¥{{ scope.row.buyPrice }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="支持购买" align="center" prop="isBuyable" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isBuyable ? 'success' : 'info'" size="mini">
            {{ scope.row.isBuyable ? '支持' : '仅租' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总库存" align="center" prop="totalStock" width="80" />
      <el-table-column label="可用库存" align="center" prop="availableStock" width="80">
        <template slot-scope="scope">
          <span :style="{color: scope.row.availableStock <= scope.row.minStockAlert ? '#F56C6C' : '#67C23A'}">
            {{ scope.row.availableStock }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="产品状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)" size="mini">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus" width="90">
        <template slot-scope="scope">
          <el-tag :type="getAuditStatusType(scope.row.auditStatus)" size="mini">
            {{ getAuditStatusText(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="质量等级" align="center" prop="qualityGrade" width="80">
        <template slot-scope="scope">
          <el-tag :type="getQualityType(scope.row.qualityGrade)" size="mini">
            {{ scope.row.qualityGrade }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplierName" width="120" show-overflow-tooltip />
      <el-table-column label="平均评分" align="center" prop="avgRating" width="80">
        <template slot-scope="scope">
          <el-rate v-model="scope.row.avgRating" disabled show-score text-color="#ff9900" score-template="{value}" style="display: inline-block;" />
        </template>
      </el-table-column>
      <el-table-column label="统计" align="center" width="120">
        <template slot-scope="scope">
          <div style="font-size: 12px; line-height: 1.2;">
            <div>浏览: {{ scope.row.viewCount || 0 }}</div>
            <div>租赁: {{ scope.row.rentCount || 0 }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:rentalDeviceProducts:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:rentalDeviceProducts:remove']"
            style="color: #F56C6C;"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 优化的添加或修改设备产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基础信息 -->
          <el-tab-pane label="基础信息" name="basic">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编码" prop="productCode">
                  <el-input v-model="form.productCode" placeholder="产品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="form.productName" placeholder="产品名称" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
            <el-form-item label="分类ID" prop="categoryId">
                  <el-input-number v-model="form.categoryId" :min="1" placeholder="分类ID" style="width: 100%" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
            <el-form-item label="品牌" prop="brand">
                  <el-input v-model="form.brand" placeholder="品牌" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
            <el-form-item label="型号" prop="model">
                  <el-input v-model="form.model" placeholder="型号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主图片">
              <image-upload v-model="form.mainImage"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
                <el-form-item label="产品描述" prop="description">
                  <el-input v-model="form.description" type="textarea" :rows="3" placeholder="产品描述" />
            </el-form-item>
          </el-col>
                        <el-col :span="24">
                <el-form-item label="规格参数" prop="specifications">
                  <div class="json-editor-container">
                    <div class="json-editor-header">
                      <span>规格参数配置</span>
                      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addSpecification">添加规格</el-button>
                    </div>
                    <div class="specifications-list">
                      <div v-for="(spec, index) in specificationsList" :key="index" class="spec-item">
                        <el-row :gutter="10" type="flex" align="middle">
                          <el-col :span="6">
                            <el-input v-model="spec.key" placeholder="规格名称" size="small" />
                          </el-col>
                          <el-col :span="16">
                            <el-tag
                              v-for="(value, vIndex) in spec.values"
                              :key="vIndex"
                              closable
                              @close="removeSpecValue(index, vIndex)"
                              style="margin-right: 5px; margin-bottom: 5px;"
                            >
                              {{ value }}
                            </el-tag>
                            <el-input
                              v-if="spec.inputVisible"
                              v-model="spec.inputValue"
                              ref="saveTagInput"
                              size="small"
                              style="width: 100px;"
                              @keyup.enter.native="handleSpecInputConfirm(index)"
                              @blur="handleSpecInputConfirm(index)"
                            />
                            <el-button v-else size="small" @click="showSpecInput(index)">+ 添加值</el-button>
                          </el-col>
                          <el-col :span="2">
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeSpecification(index)" />
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                    <div class="json-preview">
                      <el-collapse>
                        <el-collapse-item title="JSON预览" name="spec-preview">
                          <pre>{{ JSON.stringify(specificationsObject, null, 2) }}</pre>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="产品特色" prop="features">
                  <div class="json-editor-container">
                    <div class="json-editor-header">
                      <span>产品特色配置</span>
                      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addFeature">添加特色</el-button>
                    </div>
                    <div class="features-list">
                      <el-tag
                        v-for="(feature, index) in featuresList"
                        :key="index"
                        closable
                        @close="removeFeature(index)"
                        style="margin-right: 8px; margin-bottom: 8px;"
                        size="medium"
                      >
                        {{ feature }}
                      </el-tag>
                      <el-input
                        v-if="featureInputVisible"
                        v-model="featureInputValue"
                        ref="saveFeatureInput"
                        size="small"
                        style="width: 120px;"
                        @keyup.enter.native="handleFeatureInputConfirm"
                        @blur="handleFeatureInputConfirm"
                      />
                      <el-button v-else size="small" @click="showFeatureInput">+ 添加特色</el-button>
                    </div>
                    <div class="json-preview">
                      <el-collapse>
                        <el-collapse-item title="JSON预览" name="feature-preview">
                          <pre>{{ JSON.stringify(featuresList, null, 2) }}</pre>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 价格库存 -->
          <el-tab-pane label="价格库存" name="price">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="日租金(元)" prop="baseDailyRent">
                  <el-input-number v-model="form.baseDailyRent" :min="0" :precision="2" placeholder="日租金" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="押金(元)" prop="baseDeposit">
                  <el-input-number v-model="form.baseDeposit" :min="0" :precision="2" placeholder="押金" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="一口价(元)" prop="buyPrice">
                  <el-input-number v-model="form.buyPrice" :min="0" :precision="2" placeholder="一口价" style="width: 100%" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="最少租期" prop="minRentDays">
                  <el-input-number v-model="form.minRentDays" :min="1" placeholder="天数" style="width: 100%" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="最多租期" prop="maxRentDays">
                  <el-input-number v-model="form.maxRentDays" :min="1" placeholder="天数" style="width: 100%" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="支持购买" prop="isBuyable">
                  <el-switch v-model="form.isBuyable" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="总库存" prop="totalStock">
                  <el-input-number v-model="form.totalStock" :min="0" placeholder="总库存" style="width: 100%" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="可用库存" prop="availableStock">
                  <el-input-number v-model="form.availableStock" :min="0" placeholder="可用库存" style="width: 100%" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="预留库存" prop="reservedStock">
                  <el-input-number v-model="form.reservedStock" :min="0" placeholder="预留库存" style="width: 100%" />
            </el-form-item>
          </el-col>
                        <el-col :span="24">
                <el-form-item label="折扣规则" prop="discountRules">
                  <div class="json-editor-container">
                    <div class="json-editor-header">
                      <span>折扣规则配置</span>
                      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addDiscountRule">添加规则</el-button>
                    </div>
                    <div class="discount-rules-list">
                      <div v-for="(rule, index) in discountRulesList" :key="index" class="spec-item">
                        <el-row :gutter="10" type="flex" align="middle">
                          <el-col :span="8">
                            <el-input v-model="rule.key" placeholder="规则名称" size="small" @input="updateDiscountRulesForm" />
                          </el-col>
                          <el-col :span="12">
                            <el-input-number v-model="rule.value" :min="0" :max="1" :step="0.01" :precision="2" placeholder="折扣率" size="small" style="width: 100%" @change="updateDiscountRulesForm" />
                          </el-col>
                          <el-col :span="4">
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeDiscountRule(index)" />
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                    <div class="json-preview">
                      <el-collapse>
                        <el-collapse-item title="JSON预览" name="discount-preview">
                          <pre>{{ JSON.stringify(discountRulesObject, null, 2) }}</pre>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 状态管理 -->
          <el-tab-pane label="状态管理" name="status">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="产品状态" prop="status">
                  <el-select v-model="form.status" placeholder="选择状态" style="width: 100%">
                    <el-option label="下架" :value="0" />
                    <el-option label="上架" :value="1" />
                    <el-option label="预售" :value="2" />
                    <el-option label="缺货" :value="3" />
                    <el-option label="停产" :value="4" />
                  </el-select>
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="销售状态" prop="saleStatus">
                  <el-select v-model="form.saleStatus" placeholder="销售状态" style="width: 100%">
                    <el-option label="暂停销售" :value="0" />
                    <el-option label="正常销售" :value="1" />
                    <el-option label="限量销售" :value="2" />
                  </el-select>
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="审核状态" prop="auditStatus">
                  <el-select v-model="form.auditStatus" placeholder="审核状态" style="width: 100%">
                    <el-option label="待审核" :value="0" />
                    <el-option label="审核通过" :value="1" />
                    <el-option label="审核拒绝" :value="2" />
                  </el-select>
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="质量等级" prop="qualityGrade">
                  <el-select v-model="form.qualityGrade" placeholder="质量等级" style="width: 100%">
                    <el-option label="A - 全新" value="A" />
                    <el-option label="B - 99新" value="B" />
                    <el-option label="C - 95新" value="C" />
                    <el-option label="D - 90新" value="D" />
                  </el-select>
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="质保期(天)" prop="warrantyPeriod">
                  <el-input-number v-model="form.warrantyPeriod" :min="0" placeholder="质保期" style="width: 100%" />
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item label="保养周期(天)" prop="maintenanceCycle">
                  <el-input-number v-model="form.maintenanceCycle" :min="1" placeholder="保养周期" style="width: 100%" />
            </el-form-item>
          </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 服务信息 -->
          <el-tab-pane label="服务信息" name="service">
            <el-row :gutter="20">
                        <el-col :span="12">
                <el-form-item label="配送方式" prop="deliveryMethods">
                  <div class="json-editor-container">
                    <div class="json-editor-header">
                      <span>配送方式配置</span>
                      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addDeliveryMethod">添加方式</el-button>
                    </div>
                    <div class="features-list">
                      <el-tag
                        v-for="(method, index) in deliveryMethodsList"
                        :key="index"
                        closable
                        @close="removeDeliveryMethod(index)"
                        style="margin-right: 8px; margin-bottom: 8px;"
                        size="medium"
                        type="success"
                      >
                        {{ method }}
                      </el-tag>
                      <el-input
                        v-if="deliveryInputVisible"
                        v-model="deliveryInputValue"
                        ref="saveDeliveryInput"
                        size="small"
                        style="width: 120px;"
                        @keyup.enter.native="handleDeliveryInputConfirm"
                        @blur="handleDeliveryInputConfirm"
                      />
                      <el-button v-else size="small" @click="showDeliveryInput">+ 添加方式</el-button>
                    </div>
                    <div class="json-preview">
                      <el-collapse>
                        <el-collapse-item title="JSON预览" name="delivery-preview">
                          <pre>{{ JSON.stringify(deliveryMethodsList, null, 2) }}</pre>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商" prop="supplierName">
                  <el-input v-model="form.supplierName" placeholder="供应商名称" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="服务区域" prop="serviceAreas">
                  <div class="json-editor-container">
                    <div class="json-editor-header">
                      <span>服务区域配置</span>
                      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addServiceArea">添加区域</el-button>
                    </div>
                    <div class="features-list">
                      <el-tag
                        v-for="(area, index) in serviceAreasList"
                        :key="index"
                        closable
                        @close="removeServiceArea(index)"
                        style="margin-right: 8px; margin-bottom: 8px;"
                        size="medium"
                        type="warning"
                      >
                        {{ area }}
                      </el-tag>
                      <el-input
                        v-if="serviceAreaInputVisible"
                        v-model="serviceAreaInputValue"
                        ref="saveServiceAreaInput"
                        size="small"
                        style="width: 120px;"
                        @keyup.enter.native="handleServiceAreaInputConfirm"
                        @blur="handleServiceAreaInputConfirm"
                      />
                      <el-button v-else size="small" @click="showServiceAreaInput">+ 添加区域</el-button>
                    </div>
                    <div class="json-preview">
                      <el-collapse>
                        <el-collapse-item title="JSON预览" name="service-area-preview">
                          <pre>{{ JSON.stringify(serviceAreasList, null, 2) }}</pre>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
          <el-col :span="24">
                <el-form-item label="售后服务" prop="afterSalesService">
                  <el-input v-model="form.afterSalesService" type="textarea" :rows="3" placeholder="售后服务说明" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="保险信息" prop="insuranceInfo">
                  <el-input v-model="form.insuranceInfo" type="textarea" :rows="2" placeholder="保险信息说明" />
            </el-form-item>
          </el-col>
        </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRentalDeviceProducts, getRentalDeviceProducts, delRentalDeviceProducts, addRentalDeviceProducts, updateRentalDeviceProducts } from "@/api/system/rentalDeviceProducts";

export default {
  name: "RentalDeviceProducts",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备产品（商城）表格数据
      rentalDeviceProductsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前激活的标签页
      activeTab: 'basic',
      // 规格参数可视化编辑
      specificationsList: [],
      // 产品特色可视化编辑
      featuresList: [],
      featureInputVisible: false,
      featureInputValue: '',
      // 折扣规则可视化编辑
      discountRulesList: [],
      // 配送方式可视化编辑
      deliveryMethodsList: [],
      deliveryInputVisible: false,
      deliveryInputValue: '',
      // 服务区域可视化编辑
      serviceAreasList: [],
      serviceAreaInputVisible: false,
      serviceAreaInputValue: '',
      // 查询参数（精简版）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: null,
        productName: null,
        brand: null,
        model: null,
        status: null,
        auditStatus: null,
        isBuyable: null,
        supplierName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productCode: [
          { required: true, message: "产品编码不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "分类ID不能为空", trigger: "blur" }
        ],
        brand: [
          { required: true, message: "品牌不能为空", trigger: "blur" }
        ],
        model: [
          { required: true, message: "型号不能为空", trigger: "blur" }
        ],
        baseDailyRent: [
          { required: true, message: "基础日租金不能为空", trigger: "blur" }
        ],
        baseDeposit: [
          { required: true, message: "基础押金不能为空", trigger: "blur" }
        ],
        totalStock: [
          { required: true, message: "总库存数量不能为空", trigger: "blur" }
        ],
        availableStock: [
          { required: true, message: "可用库存不能为空", trigger: "blur" }
        ],
        reservedStock: [
          { required: true, message: "预留库存不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "产品状态：0-下架，1-上架，2-预售，3-缺货，4-停产不能为空", trigger: "change" }
        ],
        saleStatus: [
          { required: true, message: "销售状态：0-暂停销售，1-正常销售，2-限量销售不能为空", trigger: "change" }
        ],
        auditStatus: [
          { required: true, message: "审核状态：0-待审核，1-审核通过，2-审核拒绝不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    // 规格参数对象
    specificationsObject() {
      const obj = {};
      this.specificationsList.forEach(spec => {
        if (spec.key && spec.values.length > 0) {
          obj[spec.key] = spec.values.length === 1 ? spec.values[0] : spec.values;
        }
      });
      return obj;
    },
    // 折扣规则对象
    discountRulesObject() {
      const obj = {};
      this.discountRulesList.forEach(rule => {
        if (rule.key && rule.value != null) {
          obj[rule.key] = rule.value;
        }
      });
      return obj;
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备产品（商城）列表 */
    getList() {
      this.loading = true;
      listRentalDeviceProducts(this.queryParams).then(response => {
        this.rentalDeviceProductsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productCode: null,
        productName: null,
        categoryId: null,
        brand: null,
        model: null,
        productType: 'standard',
        specifications: null,
        description: null,
        features: null,
        mainImage: null,
        images: null,
        videos: null,
        baseDailyRent: null,
        baseDeposit: null,
        minRentDays: 1,
        maxRentDays: 365,
        discountRules: null,
        buyPrice: null,
        isBuyable: 1,
        totalStock: 0,
        availableStock: 0,
        reservedStock: 0,
        minStockAlert: 1,
        status: 1,
        saleStatus: 1,
        auditStatus: 0,
        deliveryMethods: null,
        serviceAreas: null,
        afterSalesService: null,
        insuranceInfo: null,
        qualityGrade: 'A',
        warrantyPeriod: 365,
        maintenanceCycle: 30,
        supplierId: null,
        supplierName: null,
        supplierProductCode: null
      };
      this.activeTab = 'basic';
      this.resetJsonEditors();
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备产品（商城）";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids
      getRentalDeviceProducts(productId).then(response => {
        this.form = response.data;
        // 初始化所有JSON编辑器
        this.initSpecificationsFromForm();
        this.initFeaturesFromForm();
        this.initDiscountRulesFromForm();
        this.initDeliveryMethodsFromForm();
        this.initServiceAreasFromForm();
        this.open = true;
        this.title = "修改设备产品（商城）";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 提交前同步所有JSON数据
      this.updateSpecificationsForm();
      this.updateFeaturesForm();
      this.updateDiscountRulesForm();
      this.updateDeliveryMethodsForm();
      this.updateServiceAreasForm();
      
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateRentalDeviceProducts(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRentalDeviceProducts(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal.confirm('是否确认删除设备产品（商城）编号为"' + productIds + '"的数据项？').then(function() {
        return delRentalDeviceProducts(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/rentalDeviceProducts/export', {
        ...this.queryParams
      }, `rentalDeviceProducts_${new Date().getTime()}.xlsx`)
    },
    
    // 获取状态显示文本和类型的辅助方法
    getStatusText(status) {
      const statusMap = {
        0: '下架',
        1: '上架', 
        2: '预售',
        3: '缺货',
        4: '停产'
      }
      return statusMap[status] || '未知'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'danger',
        1: 'success',
        2: 'warning', 
        3: 'info',
        4: 'danger'
      }
      return typeMap[status] || ''
    },
    getAuditStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝'
      }
      return statusMap[status] || '未知'
    },
    getAuditStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger'
      }
      return typeMap[status] || ''
    },
    getQualityType(grade) {
      const typeMap = {
        'A': 'success',
        'B': 'primary',
        'C': 'warning',
        'D': 'info'
      }
      return typeMap[grade] || ''
    },

    // ========== 规格参数可视化编辑方法 ==========
    addSpecification() {
      this.specificationsList.push({
        key: '',
        values: [],
        inputVisible: false,
        inputValue: ''
      });
    },
    removeSpecification(index) {
      this.specificationsList.splice(index, 1);
      this.updateSpecificationsForm();
    },
    showSpecInput(index) {
      this.$set(this.specificationsList[index], 'inputVisible', true);
      this.$nextTick(() => {
        if (this.$refs.saveTagInput && this.$refs.saveTagInput[index]) {
          this.$refs.saveTagInput[index].$refs.input.focus();
        }
      });
    },
    handleSpecInputConfirm(index) {
      const spec = this.specificationsList[index];
      const inputValue = spec.inputValue;
      if (inputValue && !spec.values.includes(inputValue)) {
        spec.values.push(inputValue);
      }
      spec.inputVisible = false;
      spec.inputValue = '';
      this.updateSpecificationsForm();
    },
    removeSpecValue(specIndex, valueIndex) {
      this.specificationsList[specIndex].values.splice(valueIndex, 1);
      this.updateSpecificationsForm();
    },
    updateSpecificationsForm() {
      this.form.specifications = JSON.stringify(this.specificationsObject);
    },

    // ========== 产品特色可视化编辑方法 ==========
    addFeature() {
      this.showFeatureInput();
    },
    removeFeature(index) {
      this.featuresList.splice(index, 1);
      this.updateFeaturesForm();
    },
    showFeatureInput() {
      this.featureInputVisible = true;
      this.$nextTick(() => {
        if (this.$refs.saveFeatureInput) {
          this.$refs.saveFeatureInput.$refs.input.focus();
        }
      });
    },
    handleFeatureInputConfirm() {
      const inputValue = this.featureInputValue;
      if (inputValue && !this.featuresList.includes(inputValue)) {
        this.featuresList.push(inputValue);
      }
      this.featureInputVisible = false;
      this.featureInputValue = '';
      this.updateFeaturesForm();
    },
    updateFeaturesForm() {
      this.form.features = JSON.stringify(this.featuresList);
    },

    // ========== 初始化JSON数据方法 ==========
    initSpecificationsFromForm() {
      try {
        if (this.form.specifications) {
          const specs = JSON.parse(this.form.specifications);
          this.specificationsList = Object.keys(specs).map(key => ({
            key: key,
            values: Array.isArray(specs[key]) ? specs[key] : [specs[key]],
            inputVisible: false,
            inputValue: ''
          }));
        } else {
          this.specificationsList = [];
        }
      } catch (e) {
        console.warn('规格参数JSON解析失败:', e);
        this.specificationsList = [];
      }
    },
    initFeaturesFromForm() {
      try {
        if (this.form.features) {
          this.featuresList = JSON.parse(this.form.features);
        } else {
          this.featuresList = [];
        }
      } catch (e) {
        console.warn('产品特色JSON解析失败:', e);
        this.featuresList = [];
      }
    },

    // ========== 折扣规则可视化编辑方法 ==========
    addDiscountRule() {
      this.discountRulesList.push({
        key: '',
        value: 0.8
      });
    },
    removeDiscountRule(index) {
      this.discountRulesList.splice(index, 1);
      this.updateDiscountRulesForm();
    },
    updateDiscountRulesForm() {
      this.form.discountRules = JSON.stringify(this.discountRulesObject);
    },

    // ========== 配送方式可视化编辑方法 ==========
    addDeliveryMethod() {
      this.showDeliveryInput();
    },
    removeDeliveryMethod(index) {
      this.deliveryMethodsList.splice(index, 1);
      this.updateDeliveryMethodsForm();
    },
    showDeliveryInput() {
      this.deliveryInputVisible = true;
      this.$nextTick(() => {
        if (this.$refs.saveDeliveryInput) {
          this.$refs.saveDeliveryInput.$refs.input.focus();
        }
      });
    },
    handleDeliveryInputConfirm() {
      const inputValue = this.deliveryInputValue;
      if (inputValue && !this.deliveryMethodsList.includes(inputValue)) {
        this.deliveryMethodsList.push(inputValue);
      }
      this.deliveryInputVisible = false;
      this.deliveryInputValue = '';
      this.updateDeliveryMethodsForm();
    },
    updateDeliveryMethodsForm() {
      this.form.deliveryMethods = JSON.stringify(this.deliveryMethodsList);
    },

    // ========== 服务区域可视化编辑方法 ==========
    addServiceArea() {
      this.showServiceAreaInput();
    },
    removeServiceArea(index) {
      this.serviceAreasList.splice(index, 1);
      this.updateServiceAreasForm();
    },
    showServiceAreaInput() {
      this.serviceAreaInputVisible = true;
      this.$nextTick(() => {
        if (this.$refs.saveServiceAreaInput) {
          this.$refs.saveServiceAreaInput.$refs.input.focus();
        }
      });
    },
    handleServiceAreaInputConfirm() {
      const inputValue = this.serviceAreaInputValue;
      if (inputValue && !this.serviceAreasList.includes(inputValue)) {
        this.serviceAreasList.push(inputValue);
      }
      this.serviceAreaInputVisible = false;
      this.serviceAreaInputValue = '';
      this.updateServiceAreasForm();
    },
    updateServiceAreasForm() {
      this.form.serviceAreas = JSON.stringify(this.serviceAreasList);
    },

    // ========== 扩展的初始化JSON数据方法 ==========
    initDiscountRulesFromForm() {
      try {
        if (this.form.discountRules) {
          const rules = JSON.parse(this.form.discountRules);
          this.discountRulesList = Object.keys(rules).map(key => ({
            key: key,
            value: rules[key]
          }));
        } else {
          this.discountRulesList = [];
        }
      } catch (e) {
        console.warn('折扣规则JSON解析失败:', e);
        this.discountRulesList = [];
      }
    },
    initDeliveryMethodsFromForm() {
      try {
        if (this.form.deliveryMethods) {
          this.deliveryMethodsList = JSON.parse(this.form.deliveryMethods);
        } else {
          this.deliveryMethodsList = [];
        }
      } catch (e) {
        console.warn('配送方式JSON解析失败:', e);
        this.deliveryMethodsList = [];
      }
    },
    initServiceAreasFromForm() {
      try {
        if (this.form.serviceAreas) {
          this.serviceAreasList = JSON.parse(this.form.serviceAreas);
        } else {
          this.serviceAreasList = [];
        }
      } catch (e) {
        console.warn('服务区域JSON解析失败:', e);
        this.serviceAreasList = [];
      }
    },

    // 重写表单重置方法，包含所有JSON数据初始化
    resetJsonEditors() {
      this.specificationsList = [];
      this.featuresList = [];
      this.featureInputVisible = false;
      this.featureInputValue = '';
      this.discountRulesList = [];
      this.deliveryMethodsList = [];
      this.deliveryInputVisible = false;
      this.deliveryInputValue = '';
      this.serviceAreasList = [];
      this.serviceAreaInputVisible = false;
      this.serviceAreaInputValue = '';
    }
  }
};
</script>

<style scoped>
.json-editor-container {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 15px;
  background-color: #FAFAFA;
}

.json-editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #E4E7ED;
}

.json-editor-header span {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.spec-item {
  margin-bottom: 15px;
  padding: 12px;
  background-color: #FFFFFF;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
}

.spec-item:last-child {
  margin-bottom: 0;
}

.features-list {
  min-height: 60px;
  padding: 10px;
  background-color: #FFFFFF;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  margin-bottom: 15px;
}

.json-preview {
  margin-top: 15px;
}

.json-preview pre {
  background-color: #F5F7FA;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  max-height: 200px;
  overflow-y: auto;
}

.el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.spec-item .el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .json-editor-container {
    padding: 10px;
  }
  
  .spec-item {
    padding: 8px;
  }
}
</style>
